package net.tv90.volunteerserveradmin.service;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import net.tv90.volunteerserveradmin.dao.StudentRepository;
import net.tv90.volunteerserveradmin.dao.UserRepository;
import net.tv90.volunteerserveradmin.dao.VolunteerProjectRelationRepository;
import net.tv90.volunteerserveradmin.dao.VolunteerProjectRepository;
import net.tv90.volunteerserveradmin.exception.ServiceException;
import net.tv90.volunteerserveradmin.model.domain.Student;
import net.tv90.volunteerserveradmin.model.domain.VolunteerProject;
import net.tv90.volunteerserveradmin.model.domain.VolunteerProjectRelation;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class VolunteerProjectRelationService {

    @Resource
    private VolunteerProjectRelationRepository volunteerProjectRelationRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private StudentRepository studentRepository;
    @Resource
    private VolunteerProjectRepository volunteerProjectRepository;


    public void addStudentToProject(Long studentId, Long projectId) throws ServiceException {
        // 检查权限
        long loginId = StpUtil.getLoginIdAsLong();
        // 获取学生的性别
        Student student = studentRepository.findById(studentId)
                .orElseThrow(() -> new ServiceException("学生信息不存在！"));
        String studentGender = student.getGender();
        if(!userRepository.isAdmin(loginId) && !Objects.equals(student.getId(), studentId)) {
            throw new ServiceException("无此权限");
        }
        // 检查学生是否已选该项目
        if (volunteerProjectRelationRepository.existsByVolunteerIdAndProjectId(studentId, projectId)) {
            throw new ServiceException("该学生已经选择了该项目！");
        }
        // 获取该项目的志愿活动信息
        VolunteerProject volunteerProject = volunteerProjectRepository.findById(projectId)
                .orElseThrow(() -> new ServiceException("志愿活动不存在！"));
        // 1. 检查人数上限
        long currentVolunteerCount = volunteerProjectRelationRepository.countByProjectId(projectId);
        if (currentVolunteerCount >= volunteerProject.getMaxVolunteerNum()) {
            throw new ServiceException("该项目已经达到最大志愿者人数！");
        }
        // 2. 检查性别限制
        if (volunteerProject.getGenderLimit() == 1 && !"男".equals(studentGender)) {
            throw new ServiceException("该项目仅限男性参与！");
        } else if (volunteerProject.getGenderLimit() == 2 && !"女".equals(studentGender)) {
            throw new ServiceException("该项目仅限女性参与！");
        }
        // 3. 检查报名截止时间
        LocalDateTime deadline = volunteerProject.getSignEndTime();
        if (deadline != null && LocalDateTime.now().isAfter(deadline)) {
            throw new ServiceException("该项目的报名时间已截止！");
        }
        // 4. 检查状态
        Integer status = volunteerProject.getStatus();
        if (status != 0) {
            throw new ServiceException("该活动已经开始，无法继续报名！");
        }
        // 创建新的关系并保存
        VolunteerProjectRelation relation = new VolunteerProjectRelation();
        relation.setVolunteerId(studentId);
        relation.setProjectId(projectId);
        relation.setParticipationTime(LocalDateTime.now()); // 设置参与时间
        volunteerProjectRelationRepository.save(relation);
    }

    public void removeStudentFromProject(Long studentId, Long projectId) throws ServiceException {
        // 检查权限
        long loginId = StpUtil.getLoginIdAsLong();
        // 检查学生信息是否存在
        Student student = studentRepository.findById(studentId)
                .orElseThrow(() -> new ServiceException("学生信息不存在！"));
        // 权限校验
        if (!userRepository.isAdmin(loginId) && !Objects.equals(student.getId(), studentId)) {
            throw new ServiceException("无此权限！");
        }
        // 检查项目信息是否存在
        VolunteerProject volunteerProject = volunteerProjectRepository.findById(projectId)
                .orElseThrow(() -> new ServiceException("志愿活动不存在！"));
        // 检查关系是否存在
        VolunteerProjectRelation relation = volunteerProjectRelationRepository
                .findByVolunteerIdAndProjectId(studentId, projectId);
        // 1. 检查活动状态（例如，活动是否已结束）
        Integer status = volunteerProject.getStatus();
        if (status != 0) {
            throw new ServiceException("该活动已开始或已结束，无法退出！");
        }
        // 删除关系
        volunteerProjectRelationRepository.delete(relation);
    }

}
